{% extends 'user/base.html' %}
{% block content %}

<section class="slice bg-surface-secondary">
    <div class="container mb-5 pl-6  ">
        <div class="row">
            <div class="col col-md-3 mb-sm-4">
                <div class="col col-md12">
                    <div class="card-header pb-2 list-group-item-info">
                        个人信息
                    </div>
                    <ul class="list-group list-group-flush" id="myList">
                        <li class="list-group-item"><a href="{{ url_for('users.userInfo') }}" class="link-primary">个人资料</a></li>
                        <li class="list-group-item"><a href="{{ url_for('address.address_management') }}" class="link-primary">地址管理</a></li>
                        <li class="list-group-item"><a href="{{ url_for('user.order_management') }}" class="link-primary">订单管理</a></li>
                        <li class="list-group-item" style="background-color: #cefaff;">
                            <a href="{{ url_for('story.upload_story') }}" class="link-primary">上传故事管理</a>
                        </li>
                    </ul>
                    <div class="card-footer pb-2 list-group-item-info">
                        <p></p>
                    </div>
                </div>
            </div>
            <div class="col col-md-8 col-sm-12 ml-2 pl-5 resume_box_body">
                <h2 class="text-center">{{ '编辑故事文章' if article else '上传故事文章' }}</h2>
                <form action="{{ url_for('story.upload_article', art_id=article.id if article else 0) }}" method="POST" class="mt-4" id="uploadForm">
                    <div class="form-group">
                        <label for="articleTitle">文章标题</label>
                        <input type="text" class="form-control" name="title" id="articleTitle" placeholder="请输入文章标题" value="{{ article.title if article else '' }}" required>
                    </div>
                    <!-- 富文本模板文件-->
                    <div class="form-group">
                        <!-- 工具栏容器 -->
                        <div id="toolbar-container"></div>
                        <!-- 编辑器容器 -->
                        <div id="editor-container" style="border: 1px solid #ccc; height: 400px;"></div>
                        <textarea hidden name="content" id="editor-content"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="articleCategory">选择分类</label>
                        <select class="form-control" name="category_id" id="articleCategory" required>
                            <option value="">请选择分类</option>
                            {% for category in categories %}
                                <option value="{{ category.id }}" {% if article and article.category_id == category.id %}selected{% endif %}>{{ category.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="text-center">
                        <button type="submit" class="btn btn-primary">保存文章</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</section>

<!-- 引入依赖 -->
<!-- wangEditor -->
<link href="{{ url_for('static', filename='front/css/vender/wangEditor.css') }}" rel="stylesheet">
<script src="{{ url_for('static', filename='front/js/wangEditor.js') }}"></script>

<script>
// 初始化顺序修正
const { createEditor, createToolbar } = window.wangEditor;

// 编辑器容器
const editorContainer = '#editor-container';
// 工具栏容器
const toolbarContainer = '#toolbar-container';

// 创建编辑器实例
const editor = createEditor({
    selector: editorContainer,
    // 编辑器配置
    config: {
        placeholder: '请输入内容...',
        onChange(editor) {
            document.getElementById('editor-content').value = editor.getHtml();
        }
    },
    mode: 'default'
});

// 创建工具栏（必须在编辑器之后）
const toolbar = createToolbar({
    editor,
    selector: toolbarContainer,
    // 工具栏配置
    config: {
        excludeKeys: ['insertVideo'],
        uploadImage: {
            server: '/upload-file',
            fieldName: 'image',
            maxFileSize: 3 * 1024 * 1024,
            allowedFileTypes: ['image/*'],
            onSuccess(file, res) {
                return res.url;
            }
        }
    }
});

// 安全初始化内容
{% if article %}
editor.setHtml({{ article.content|tojson|safe }});
document.getElementById('editor-content').value = {{ article.content|tojson|safe }};
{% endif %}

// 表单提交处理
document.getElementById('uploadForm').onsubmit = async function(event) {
    event.preventDefault();

    // 添加加载状态
    const submitBtn = this.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '保存中...';

    try {
        const formData = new FormData(this);
        const response = await fetch(this.action, {
            method: 'POST',
            body: formData,
            headers: { 'Accept': 'application/json' }
        });
        // 处理非JSON响应
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            const text = await response.text();
            throw new Error(`无效响应: ${text.slice(0, 100)}`);
        }
        const result = await response.json();
        if (result.success) {
            window.location.href = result.redirect_url;
        } else {
            alert(`保存失败: ${result.error}`);
        }
    } catch (error) {
        console.error('提交失败:', error);
        alert(`请求错误: ${error.message}`);
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '保存文章';
    }
};
</script>
{% endblock %} 